package com.epfresh.supplier.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.dialog.PackagePriceDialog;
import com.epfresh.api.global.AppActivity;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.FormatUtil;
import com.epfresh.supplier.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzh on 16-7-25.
 */
public class ProductAddPriceMoqActivity extends AppActivity {


    private TextView tvPackageUnit;
    private TextView tvTitle;
    private EditText edPackage;

    private View vPreTips;
    private View vFlag;
    private RelativeLayout rl_choose_price_unit;

    private String unit;
    private String value;
    private String productId;
    private String price;
    private int saleType = 1;
    private List<String> priceUnit ;

    private String priceUnitStr;
    private String priceUnitStrDraft;
    private String moq;
//    private String chargeUnit;

    private TextView tvMoq;
    private TextView tvBtn;
    private TextView tvUnit;
    private View vAdd;
    private View vReduce;


    private Double incr = 0.01d;
    String packageContainer;
    String packageUnit;
    String packageSize;
    String weight;
    private String listType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_product_price_moq);

        if (savedInstanceState != null) {
            getIntent().putExtra("productId", savedInstanceState.getString("productId"));
            getIntent().putExtra("price", savedInstanceState.getString("price"));
            getIntent().putExtra("type", savedInstanceState.getInt("type", -1));
            getIntent().putExtra("unit", savedInstanceState.getString("unit"));
            getIntent().putExtra("value", savedInstanceState.getString("value"));
            getIntent().putExtra("saleType", savedInstanceState.getInt("saleType"));
            getIntent().putExtra("incr", savedInstanceState.getInt("incr", 1));
            getIntent().putExtra("priceUnit", savedInstanceState.getString("priceUnit"));
            getIntent().putExtra("moq", savedInstanceState.getString("moq"));
            getIntent().putExtra("packageContainer", savedInstanceState.getString("packageContainer"));
            getIntent().putExtra("packageUnit", savedInstanceState.getString("packageUnit"));
            getIntent().putExtra("packageSize", savedInstanceState.getString("packageSize"));
            getIntent().putExtra("weight", savedInstanceState.getString("weight"));

        }
        packageContainer = getIntent().getStringExtra("packageContainer");
        packageUnit = getIntent().getStringExtra("packageUnit");
        packageSize = getIntent().getStringExtra("packageSize");
        weight = getIntent().getStringExtra("weight");
        incr = getIntent().getDoubleExtra("incr", 0.01);
        moq = getIntent().getStringExtra("moq");
        listType = getIntent().getStringExtra("listType");
        String s = "价格及起订量 <font color=\"#ff0000\">*</font>";
        toolbarTitle.setText(Html.fromHtml(s));
        ivBack.setVisibility(View.VISIBLE);
        tvBack.setVisibility(View.VISIBLE);

        rightbtn.setText("");

        rightbtn.setVisibility(View.VISIBLE);

        tvPackageUnit = (TextView) findViewById(R.id.tv_package);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        edPackage = (EditText) findViewById(R.id.ed_package);
        vPreTips =  findViewById(R.id.rl_refuse_reason);
        vFlag =  findViewById(R.id.iv_flag);
        rl_choose_price_unit =  findViewById(R.id.rl_choose_price_unit);

        tvPackageUnit.setOnClickListener(this);
        CashierInputFilter cashierInputFilter = new CashierInputFilter();
        cashierInputFilter.MAX_VALUE = 9999999;
        edPackage.setFilters(new InputFilter[]{cashierInputFilter});
        findViewById(R.id.tv_btn).setOnClickListener(this);


        unit = getIntent().getStringExtra("unit");

//        chargeUnit = unit;
        value = getIntent().getStringExtra("price");
        productId = getIntent().getStringExtra("productId");
        price = getIntent().getStringExtra("price");
        edPackage.setText(value);
        edPackage.setSelection(edPackage.length());

        priceUnitStr = getIntent().getStringExtra("priceUnit");
        if (priceUnitStr != null && !"".equals(priceUnitStr)){
            priceUnit = new Gson().fromJson(priceUnitStr,new TypeToken<List<String>>(){}.getType());
        } else {
            priceUnitStrDraft = getIntent().getStringExtra("productPriceUnit");
            if (priceUnitStrDraft != null && !"".equals(priceUnitStrDraft)){
            priceUnit = new Gson().fromJson(priceUnitStrDraft,new TypeToken<List<String>>(){}.getType());
            }
        }

        if (priceUnit == null){
            priceUnit = new ArrayList<>();
        }
        Log.e("unit","unit:"+unit);
        Log.e("unit","priceUnitStr:"+priceUnitStr);
        Log.e("unit","incr:"+incr);
        if (priceUnit.size() == 0){
            vFlag.setVisibility(View.INVISIBLE);
//            vFlag.setOnClickListener(null);
            rl_choose_price_unit.setOnClickListener(null);
        }else {
            //如果是'草稿状态'或者发布新商品时，则能选择  (发布新商品时从上个页面传递过来的listType未默认值-1)
            if (listType.equals("0")||listType.equals("-1")) {
                vFlag.setVisibility(View.VISIBLE);
//                vFlag.setOnClickListener(this);
                rl_choose_price_unit.setOnClickListener(this);
            }

        }

        if (listType.equals("1")) {
            vFlag.setVisibility(View.INVISIBLE);
        }

        if (!TextUtils.isEmpty(unit)) {
            tvPackageUnit.setText("元/" + unit);
        } else {
            tvPackageUnit.setText("元");
        }

        saleType = getIntent().getIntExtra("saleType",1);
        if (saleType == 2){
            vPreTips.setVisibility(View.VISIBLE);
        }else {
            vPreTips.setVisibility(View.GONE);

        }



        tvMoq = (TextView) findViewById(R.id.tv_moq);
        tvBtn = (TextView) findViewById(R.id.tv_btn);
        tvUnit = (TextView) findViewById(R.id.tv_unit);
        vAdd = findViewById(R.id.iv_add);
        vReduce = findViewById(R.id.iv_remove);

        vAdd.setOnClickListener(this);
        vReduce.setOnClickListener(this);

        tvBtn.setOnClickListener(this);


        tvMoq.setText(moq);
        tvUnit.setText(unit);

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {

            case R.id.tv_btn:
                save();
                break;
            case R.id.rl_choose_price_unit:
                openUnitDialog(priceUnit);
                break;
            case R.id.iv_add:
                add(true);
                break;
            case R.id.iv_remove:
                add(false);
                break;

        }
    }


    private void add(boolean isAdd) {
        String s = tvMoq.getText().toString();
        if ("".equals(s)) {
            for (int i = 0; i < priceUnit.size(); i++) {
                String s1 = priceUnit.get(i);
//                if (s1.equals())
            }
            s = "0";
        }
        Double cnt = Double.valueOf(s);
        BigDecimal bdCnt = BigDecimal.valueOf(cnt);
        BigDecimal bdIncr = BigDecimal.valueOf(incr);
        BigDecimal add = null;
        if (isAdd) {
            add = bdCnt.add(bdIncr);

        } else {
            add = bdCnt.subtract(bdIncr);
        }

        if (add.compareTo(BigDecimal.ZERO) < 0) {
            add = BigDecimal.ZERO;
        }

        tvMoq.setText(FormatUtil.subZeroAndDot(add.toString()));
    }

    private void save() {

        if (TextUtils.isEmpty(edPackage.getText().toString())) {

            toast("请先设置价格及单位");

            return;
        }

        if (TextUtils.isEmpty(tvMoq.getText().toString()) ||  "0".equals(tvMoq.getText().toString())){
            toast("请添加起订量");

            return;
        }


        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘

//        if (productId != null && !"".equals(productId)) {
//            requestProductModify(edPackage.getText().toString());
//
//        } else {
            Intent intent = new Intent();
            intent.putExtra("price", edPackage.getText().toString());
            intent.putExtra("unit", unit);
            intent.putExtra("moq", tvMoq.getText().toString());
            setResult(RESULT_OK, intent);
            finish();

//            ProductAddEntity productAddEntity = DataManager.getInstance().getProductAddEntity();
//            productAddEntity.setChargeUnit(unit);
//            productAddEntity.setPrice(edPackage.getText().toString());
//            productAddEntity.setMoq(tvMoq.getText().toString());


//        }
    }




    public void openUnitDialog(List<String> units) {

        if (priceUnit == null || priceUnit.size() == 0){
            return;
        }
        PackagePriceDialog packageDialog = new PackagePriceDialog(this);
        packageDialog.setPositiveDismiss(true);
        packageDialog.setOnPositiveClickListener(new PackagePriceDialog.OnPositiveClickListener() {
            @Override
            public void onPositiveClickListener(int index1, String data1) {
                if (unit != null && unit.equals(data1)){
//                    unit = data1;
                }else {
                    unit = data1;
                    incr = getIncr();
                    tvMoq.setText(FormatUtil.subZeroAndDot(incr+""));
                    Log.e("incr","incr----"+incr);
                }
                tvPackageUnit.setText("元/"+data1);
                tvUnit.setText(data1);


            }
        });

        packageDialog.setData(priceUnit);

//        String packageUnit = productAddEntity.getPackageUnit();
//        String packageContainer = productAddEntity.getPackageContainer();

        if (!TextUtils.isEmpty(unit)) {
            int index1 = 0;

            for (int i = 0; i < units.size(); i++) {
                if (unit.equals(units.get(i))) {
                    index1 = i;
                }
            }

            packageDialog.setCurrentItem(index1);
        }

        packageDialog.show();
    }





    public double getIncr() {
        try {


            Log.e("chargeUnit","chargeUnit----"+unit);
            Log.e("packageContainer","packageContainer----"+packageContainer);
            Log.e("packageUnit","packageUnit----"+packageUnit);
            Log.e("weight","weight----"+weight);
//            if ("散货".equals(packageContainer)) {
//                return 1;
//            } else {
//
//            }

            if (packageContainer != null && packageContainer.equals(unit)) {
                return 1;
            } else if (packageUnit != null && packageUnit.equals(unit)) {
                if (packageSize != null && !"".equals(packageSize)) {
                    return Double.valueOf(packageSize);
                }
            } else {
                if (weight != null && !"".equals(weight)) {
                    double f = Double.valueOf(weight);
                    return f;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 1;
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putString("unit", unit);
        outState.putString("value", value);
        outState.putString("productId", productId);
        outState.putString("price", price);
        outState.putString("priceUnit", priceUnitStr);
        outState.putInt("saleType", saleType);

        outState.putString("packageContainer", packageContainer);
        outState.putString("packageUnit", packageUnit);
        outState.putString("packageSize", packageSize);
        outState.putString("weight", weight);
        super.onSaveInstanceState(outState);
    }


    @Override
    protected void onToolbarBack() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘
        super.onToolbarBack();
    }

    @Override
    public void onBackPressed() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edPackage.getWindowToken(), 0); //强制隐藏键盘
        super.onBackPressed();
    }

}
